<template>
  <el-card style="max-width:600px;margin:40px auto;">
    <template #header>
      <h2 style="color: #3998a9;">文件上传</h2>
    </template>
    <el-form :inline="true" style="margin-bottom:16px">
      <el-form-item label="目标文件夹">
        <el-select
          v-model="selectedFolder"
          placeholder="请选择文件夹"
          style="width:300px"
          clearable
          filterable
        >
          <el-option value="" label="/ (根目录)" />
          <el-option
            v-for="folder in allFolders"
            :key="folder.id"
            :value="folder.id"
            :label="folder.path || folder.name"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <el-upload class="upload-demo" drag action="#" :auto-upload="false" :file-list="fileList" :on-change="handleChange"
      :before-upload="beforeUpload" :on-remove="handleRemove" multiple :limit="5" :accept="acceptTypes">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或 <em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip">支持多种格式，单文件最大10MB</div>
      </template>
    </el-upload>
    <div style="text-align:right;margin-top:20px;">
      <el-button @click="goBack">返回列表</el-button>
      <el-button type="primary" @click="submitUpload">上传</el-button>
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'


// 文件夹选择相关
const selectedFolder = ref("")
const allFolders = ref([])


const fileList = ref([])
const acceptTypes = '.pdf,.png,.jpg,.jpeg,.xlsx,.doc,.docx,.zip,.rar,.txt'
const router = useRouter()

// 递归获取所有文件夹
function getAllFolders() {
  const storageList = JSON.parse(localStorage.getItem('fileList') || '[]')
  // 只取 type === 'folder'
  return storageList.filter(f => f.type === 'folder')
}

onMounted(() => {
  allFolders.value = getAllFolders()
  // 默认选中来源目录，且类型为字符串
  const uploadParent = sessionStorage.getItem('uploadParent')
  if (uploadParent && allFolders.value.some(f => f.id === uploadParent)) {
    selectedFolder.value = uploadParent
  } else {
    selectedFolder.value = ""
  }
})

function handleChange(file, files) {
  fileList.value = files
}
function handleRemove(file, files) {
  fileList.value = files
}
function beforeUpload(file) {
  // 文件大小限制
  if (file.size / 1024 / 1024 > 10) {
    ElMessage.error('单文件不能超过10MB')
    return false
  }
  // 文件安全检查（模拟：禁止exe/js）
  const forbidden = ['exe', 'js']
  const ext = file.name.split('.').pop().toLowerCase()
  if (forbidden.includes(ext)) {
    ElMessage.error('禁止上传可执行文件')
    return false
  }
  return true
}
function submitUpload() {
  if (!fileList.value.length) {
    ElMessage.warning('请选择文件')
    return
  }
  let storageList = JSON.parse(localStorage.getItem('fileList') || '[]')
  const now = new Date()
  const pad = n => n.toString().padStart(2, '0')
  fileList.value.forEach(file => {
    const reader = new FileReader()
    reader.onload = function (e) {
      const base64 = e.target.result
      // 生成唯一id
      const id = 'f_' + Date.now() + Math.floor(Math.random() * 1000)
      // 构造文件对象
      const fileObj = {
        id,
        name: file.name,
        type: file.raw.type || file.name.split('.').pop(),
        size: (file.size / 1024 / 1024).toFixed(2) + 'MB',
        owner: 'admin01',
        uploadTime: `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`,
        content: base64,
        path: '/uploads/' + file.name,
        parent: selectedFolder.value || null
      }
      // 避免重名（同目录下）
      storageList = storageList.filter(f => !(f.name === fileObj.name && (f.parent || null) === (selectedFolder.value || null)))
      storageList.push(fileObj)
      localStorage.setItem('fileList', JSON.stringify(storageList))
    }
    reader.readAsDataURL(file.raw)
  })
  ElMessage.success('文件上传成功')
  setTimeout(() => router.push('/file/filelist'), 500)
}
function goBack() {
  router.push('/file/filelist')
}
</script>
